<?php
namespace Home\Model;
use Think\Model;
class UserModel extends Model {
    //用户表自动完成
  protected  $_auto = array(               //MODEL_BOTH修改是执行
        array('user_password','sha1',self::MODEL_BOTH,'function'),
    );
  //批量验证
 // protected $patchValidate = true ;
  //自动验证
   protected  $_validate =array(             //EXISTS_VALIDATE 存在是执行
       //-1  账号长度不合法
       array('user_name','/^[^@]{2,20}$/i',-1 ,self::EXISTS_VALIDATE,'length'),
       //-2   密码长度不合法
       array('user_password','6,20',-2,self::EXISTS_VALIDATE,'length'),
       //-3   密码不一致
       array('repassword','user_password',-3,self::EXISTS_VALIDATE,'confirm'),
       //-4   电子邮箱格式不正确
       array('user_email','email',-4 ,self::EXISTS_VALIDATE),
       //-5   用户已被注册
       array('user_name','',-5,self::EXISTS_VALIDATE,'unique',self::MODEL_INSERT),
       //-6   电子邮箱已被注册
       array('user_email','',-6 ,self::EXISTS_VALIDATE,'unique',self::MODEL_INSERT),
       //-7  验证码验证
       array('verify' ,'check_Verify',-7,self::EXISTS_VALIDATE,'function'),
       //登录用户名长度验证
       array('login_username','2,50','-8',self::EXISTS_VALIDATE,'length'),
       //noemail 登录是否是邮箱登录
       array('login_username','email','noemail',self::EXISTS_VALIDATE,)
   );
  
   //AJAX 验证用户和电子邮件是否被注册  验证是否正确
   public function  checkField($field,$type){
       $data=array();
       switch ($type) {
           case  'user':
             $data['user_name'] = $field;
             break;
           case  'email':
             $data['user_email']= $field; 
              break;
           case  'verify':
             $data['verify']= $field; 
              break;
             default : 
                 return 0;
       }
       return $this->create($data) ?  1 : $this->getError();
   }

    //注册新用户  
  public function register($username,$password ,$repassword,$email,$verify){
      $data=array(
          'user_name'=>$username,
          'user_password'=>$password,
          'repassword'=>$repassword,
          'user_email'=>$email,
          'user_date'=> date('Y-m-d H:i:s'),
          'verify' => $verify
      );
     if($this->create($data)){
         $uid=$this->add();
         return $uid ? $uid : 0;
      }else{
         return $this->getError();
      }
  }  
  
  //登录自动验证
  public function login($username,$password){
      $data=  array(
          'login_username' => $username,
          'user_password' => $password,
      );
      
      //where  条件
      $map =array();
     if($this->create($data)){ 
        //这里是邮箱登录方式
             $map['user_email']= $username;
     }else{
        if($this->getError() == 'noemail'){
        //这里是账号登录方式
            $map['user_name']= $username;
        }else{
            return $this->getError(); 
        }
     }
     $user= $this->where($map)->find();
     if($user['user_password'] === sha1($password)){
         session("user",$user); 
         return   $user['user_id'];
     }else{
         return   -9  ; //密码不正确
     } 
  }
}
?>
